package com.fa.dv.listener;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson2.JSON;
import com.fa.dv.domain.Subject;
import com.fa.dv.service.ISubjectService;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
@Slf4j
public class SubjectReadListener implements ReadListener<Subject> {
    private ArrayList<Subject> cacheList = new ArrayList<>();
    private final int BATCH_COUNT = 3;
    private ISubjectService subjectService;

    public SubjectReadListener(ISubjectService subjectService){
        this.subjectService = subjectService;
    }

    /**
     * 读取到excel中每一行数据都会调用一次该方法
     */
    @Override
    public void invoke(Subject subject, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", JSON.toJSONString(subject));
        cacheList.add(subject);
        if (cacheList.size() >= BATCH_COUNT) {
            // 处理缓存数据
            saveData();
            // 清空缓存
            cacheList.clear();
        }
    }

    /**
     * 最后处理最后缓存中的数据
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        log.info("所有数据解析完成！");
    }
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cacheList.size());
        // 处理缓存数据的逻辑
        subjectService.saveBatch(cacheList);
        log.info("存储数据库成功！");
    }
}
